package cn.edu.fzu.homemaking.company.config;

import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.company.filter.web.CrossDomainFilter;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.ExchangeBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * @author wanjie
 * @version 1.0
 */
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = "cn.edu.fzu.homemaking")
public class CompanyConfig {

    public static final String EXCHANGE_TOPICS_ORDER = "exchange_topics_order";

    public static final String QUEUE_ORDER           = "queue_order";

    public static final String ROUTING_ORDER         = "order.#";

    @Bean
    public Docket webApi() {
        return new Docket(DocumentationType.SWAGGER_2).select()
                .apis(RequestHandlerSelectors.basePackage("cn.edu.fzu.homemaking.company.controller"))
                .paths(PathSelectors.ant("/api/**")).build().groupName("家政系统接口文档V1.0").pathMapping("/").enable(true)
                .apiInfo(new ApiInfoBuilder().title("公司端模块接口文档V1.0").description("公司端模块相关接口").version("1.0").build());
    }


    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {

        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //1、使用RequestContextHolder拿到刚进来的请求数据
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes();

                if (requestAttributes != null) {
                    //老请求
                    HttpServletRequest request = requestAttributes.getRequest();

                    //2、同步请求头的数据（主要是cookie）
                    //把老请求的cookie值放到新请求上来，进行一个同步
                    String cookie = request.getHeader("Cookie");
                    if (StringUtils.isBlank(cookie) || !cookie.contains(SessionConstant.DSESSIONID)) {
                        cookie = SessionConstant.DSESSIONID + "=" + request.getSession().getId();
                    }
                    template.header("Cookie", cookie);
                }
            }
        };
    }


    @LoadBalanced
    @Bean
    public RequestTemplate requestTemplate() {
        return new RequestTemplate();
    }


    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        //1.需要定义一个convert转换消息的对象;
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2处理ie浏览器保存数据时出现下载json数据问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.TEXT_PLAIN);
        fastMediaTypes.add(MediaType.APPLICATION_JSON);
        fastMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        //3.在convert中添加配置信息.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        return new HttpMessageConverters(fastJsonHttpMessageConverter);
    }


    @Bean
    public FilterRegistrationBean<CrossDomainFilter> crossDomainFilter() {
        FilterRegistrationBean<CrossDomainFilter> filterRegistrationBean = new FilterRegistrationBean<>();
        filterRegistrationBean.setFilter(new CrossDomainFilter());//设置过滤器名称
        filterRegistrationBean.addUrlPatterns("/*");//配置过滤规则
        filterRegistrationBean.setOrder(0); //order的数值越小 则优先级越高
        return filterRegistrationBean;
    }


    /** 声明交换机 **/
    @Bean(EXCHANGE_TOPICS_ORDER)
    public Exchange EXCHANGE_TOPICS_INFORM() {
        return ExchangeBuilder.topicExchange(EXCHANGE_TOPICS_ORDER).durable(true).build();
    }


    /** 声明队列 **/
    @Bean(QUEUE_ORDER)
    public Queue orderMessage() {
        return new Queue(QUEUE_ORDER);
    }


    @Bean
    public Binding BINDING_QUEUE_INFORM_ORDER(@Qualifier(QUEUE_ORDER) Queue queue,
                                              @Qualifier(EXCHANGE_TOPICS_ORDER) Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(ROUTING_ORDER).noargs();
    }

}
